package com.liaoban.app.ui.base;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dalong.recordlib.RecordVideoActivity;
import com.dalong.recordlib.RecordVideoUtils;
import com.liaoban.app.R;
import com.liaoban.app.constants.Constant;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.mine.VideoCertActivity;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.TakePictureManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

/**
 * 上传图片基类
 * Created by ybc on 2017/7/5.
 */

public abstract class BaseUploadPicActivity extends BaseToolbarActivity {
    public static final int TAKE_DATA = 200;
    protected TakePictureManager takePictureManager;
    protected int clickPic;
    public static final int TYPE_PIC = 1;
    public static final int TYPE_VIDEO = 2;
    protected String mVideoPath;

    /**
     * @param isTailor 是否需要裁剪
     */
    protected void showSheetDialog(boolean isTailor) {
        clickPic = TYPE_PIC;
        View view = getLayoutInflater().inflate(
                R.layout.dialog_select_pic, null);
        final Dialog dialog = new Dialog(BaseUploadPicActivity.this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        TextView tvCamera = view.findViewById(R.id.tv_to_camera);
        tvCamera.setOnClickListener(v -> {
            dialog.dismiss();
            takePictureManager = new TakePictureManager(BaseUploadPicActivity.this);
            if (isTailor) {
                //开启裁剪 比例 1:3 宽高 350 350  (默认不裁剪)
                takePictureManager.setTailor(1, 1, 350, 350);
            }
            //拍照方式
            takePictureManager.startTakeWayByCarema();
            //回调
            takePictureManager.setTakePictureCallBackListener(new TakePictureManager.takePictureCallBackListener() {
                //成功拿到图片,isTailor 是否裁剪？ ,outFile 拿到的文件 ,filePath拿到的URl
                @Override
                public void successful(boolean isTailor, File outFile, Uri filePath) {
                    uploadPicSuccessful(isTailor, outFile, filePath);
                }

                //失败回调
                @Override
                public void failed(int errorCode, List<String> deniedPermissions) {
                    Log.e("==w", deniedPermissions.toString());
                }
            });
        });
        TextView tvPhoto = view.findViewById(R.id.tv_to_photo);
        tvPhoto.setOnClickListener(v -> {
            dialog.dismiss();
            takePictureManager = new TakePictureManager(BaseUploadPicActivity.this);
            if (isTailor) {
                takePictureManager.setTailor(1, 1, 350, 350);
            }
            takePictureManager.startTakeWayByAlbum();
            takePictureManager.setTakePictureCallBackListener(new TakePictureManager.takePictureCallBackListener() {
                @Override
                public void successful(boolean isTailor, File outFile, Uri filePath) {
                    uploadPicSuccessful(isTailor, outFile, filePath);
                }

                @Override
                public void failed(int errorCode, List<String> deniedPermissions) {

                }

            });

        });
        TextView tvCancel = view.findViewById(R.id.tv_to_cancel);
        tvCancel.setOnClickListener(v -> dialog.dismiss());
    }

    /**
     * 视频
     */
    protected void showSheetVideoDialog() {
        clickPic = TYPE_VIDEO;
        View view = getLayoutInflater().inflate(
                R.layout.dialog_select_video, null);
        final Dialog dialog = new Dialog(BaseUploadPicActivity.this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        TextView tvLocalUpload = view.findViewById(R.id.tv_local_upload);
        tvLocalUpload.setOnClickListener(v -> {
            dialog.dismiss();
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, 66);
        });
        TextView tvRecord = view.findViewById(R.id.tv_record);
        tvRecord.setOnClickListener(v -> {
            dialog.dismiss();
            File path = CommonUtils.getVideoPicPath();
            mVideoPath = path.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".mp4";
            requestLocationPermission();
        });
        TextView tvCancel = view.findViewById(R.id.tv_to_cancel);
        tvCancel.setOnClickListener(v -> dialog.dismiss());
    }

    protected void uploadPicSuccessful(boolean isTailor, File outFile, Uri filePath) {
    }

    protected void uploadVideoSuccessful(String videoPath) {
    }

    protected boolean isVideoLarge(String videoPath) {
        File file = new File(videoPath);
        try {
            long size = CommonUtils.getFileSize(file);
            if (size > (2 * 1024 * 1024)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (clickPic == TYPE_PIC) {
            takePictureManager.attachToActivityForResult(requestCode, resultCode, data);
        } else if (requestCode == TAKE_DATA && resultCode == RecordVideoActivity.TAKE_VIDEO_CODE && clickPic == 2) {
            mVideoPath = data.getStringExtra(RecordVideoActivity.TAKE_VIDEO_PATH);
            uploadVideoSuccessful(mVideoPath);
        } else if (requestCode == 66 && resultCode == RESULT_OK && null != data) {
            Uri selectedVideo = data.getData();
            String[] filePathColumn = {MediaStore.Video.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedVideo,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mVideoPath = cursor.getString(columnIndex);
            cursor.close();
            uploadVideoSuccessful(mVideoPath);
        }
    }

    //onRequestPermissionsResult()方法权限回调绑定到对象
    @Override
    public void onRequestPermissionsResult(int requestCode, @android.support.annotation.NonNull String[] permissions, @android.support.annotation.NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 权限全部选择完成，才会执行回调方法
     */
    private void requestLocationPermission() {
        String[] permissions = {
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions).subscribe(aBoolean -> {
            if (aBoolean) {
                Intent intent = new Intent(BaseUploadPicActivity.this, RecordVideoActivity.class);
                intent.putExtra(RecordVideoActivity.RECORD_VIDEO_PATH, mVideoPath);
                startActivityForResult(intent, TAKE_DATA);
            } else {
                ToastHelper.show(BaseUploadPicActivity.this, "请先获取权限");
            }
        });
    }
}
